<template>
  <div class="app-container">
    <div class="filter-container">
      <SearchOptionUser type="1" @setSearchUserId="searchUserId" />
      <el-select v-model="listQuery.type" placeholder="调整类型" clearable class="filter-item" style="width: 130px">
        <el-option v-for="(value,key) in typeOptions" :key="key" :label="value" :value="key" />
      </el-select>
      <el-input v-model="listQuery.op_name" placeholder="操作人" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        添加
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :header-cell-style="{background:'#ccc',color:'black'}"
      :data="list"
      border
      stripe
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" align="center" width="80">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="用户姓名" align="center">
        <template slot-scope="{row}">
          <span>{{ row.userInfo.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调整类型" align="center">
        <template slot-scope="{row}">
          <span>{{ typeOptions[row.type] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调整原因" align="center">
        <template slot-scope="{row}">
          <span>{{ row.content }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调整前分数" align="center">
        <template slot-scope="{row}">
          <span>{{ row.before_score }}</span>
        </template>
      </el-table-column>
      <el-table-column label="调整后分数" align="center">
        <template slot-scope="{row}">
          <span>{{ row.after_score }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center">
        <template slot-scope="{row}">
          <span>{{ row.op_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center">
        <template slot-scope="{row}">
          <span>{{ row.created_at }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="230" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button type="danger" size="mini" @click="handleDelete(row,$index)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="110px" style="width: 400px; margin-left:50px;">
        <el-form-item v-if="textMap[dialogStatus] === '添加'" label="用户姓名" prop="user_id">
          <SearchOptionUser type="1" style="width:290px" @setSearchUserId="searchUpdateUserId" />
        </el-form-item>
        <el-form-item v-else label="用户姓名" prop="user_id">
          <el-input v-model="userInfoName" disabled />
        </el-form-item>
        <el-form-item label="调整类型" prop="type">
          <el-select v-model="temp.type" placeholder="调整类型" style="width:290px">
            <el-option v-for="(value,key) in typeOptions" :key="key" :label="value" :value="key" />
          </el-select>
        </el-form-item>
        <el-form-item label="调整原因" prop="content">
          <el-input v-model="temp.content" type="textarea" />
        </el-form-item>
        <el-form-item label="调整前分数" prop="before_score">
          <el-input-number v-model="temp.before_score" />
        </el-form-item>
        <el-form-item label="调整后分数" prop="after_score">
          <el-input-number v-model="temp.after_score" />
        </el-form-item>
        <el-form-item label="操作人" prop="op_name">
          <el-input v-model="temp.op_name" />
        </el-form-item>
        <el-form-item label="操作时间" prop="created_at">
          <div class="block">
            <el-date-picker
              v-model="temp.created_at"
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="操作时间"
              style="width:290px"
            />
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { scoreStudentChangePage, scoreStudentChangeUpdate, scoreStudentChangeDelete } from '@/api/xuanxiu'
import waves from '@/directive/waves' // waves directive

import { notifySuccess, formatJson, my_confirm, listQueryFilter } from '@/utils/tool'
import SearchOptionUser from '@/components/SearchOption/user'
import Pagination from '@/components/Pagination'

export default {
  name: 'ScoreStudentChange',
  components: { Pagination, SearchOptionUser },
  directives: { waves },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      typeOptions: {
        1: '信用分',
        2: '应修学分',
        3: '已修学分'
      },
      listQuery: {
        page: 1,
        limit: 20,
        user_id: null,
        type: null,
        op_name: null,
        querySort: '-id'
      },
      temp: {
        id: null,
        name: null,
        address: null,
        sort: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加'
      },
      rules: {
        user_id: [{ required: true, message: '用户名称必填', trigger: 'change' }],
        type: [{ required: true, message: '调整类型必填', trigger: 'change' }],
        content: [{ required: true, message: '调整原因必填', trigger: 'change' }],
        before_score: [{ required: true, message: '调整前分数必填', trigger: 'change' }],
        after_score: [{ required: true, message: '调整后分数必填', trigger: 'change' }],
        op_name: [{ required: true, message: '操作人必填', trigger: 'change' }],
        created_at: [{ required: true, message: '操作时间必填', trigger: 'change' }]
      },
      downloadLoading: false,
      userInfoName: ''
    }
  },
  created() {
    this.handleFilter()
  },
  methods: {
    getList() {
      this.listLoading = true
      this.listQuery = listQueryFilter(this.listQuery)
      scoreStudentChangePage(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.page
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      if (this.$route.query.user_id) { this.listQuery.user_id = this.$route.query.user_id }
      if (this.$route.query.type) { this.listQuery.type = this.$route.query.type.toString() }
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'sort') {
        this.sortByID(order, prop)
      }
    },
    sortByID(order, prop) {
      if (order === 'ascending') {
        this.listQuery.querySort = '+' + prop
      } else {
        this.listQuery.querySort = '-' + prop
      }
      this.handleFilter()
    },
    resetTemp() {
      this.temp = {
        user_id: null,
        type: null,
        content: null,
        before_score: null,
        after_score: null,
        op_name: null,
        created_at: null
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          scoreStudentChangeUpdate(this.temp).then(response => {
            var rs = response.data
            this.list.unshift(rs)
            this.dialogFormVisible = false
            notifySuccess(this, '创建成功')
            this.handleFilter()
          })
        }
      })
    },
    handleUpdate(row) {
      this.userInfoName = row.userInfo.name
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          delete this.temp.userInfo
          const tempData = Object.assign({}, this.temp)
          scoreStudentChangeUpdate(tempData).then(response => {
            var rs = response.data
            const index = this.list.findIndex(v => v.id === rs.id)
            this.list.splice(index, 1, rs)
            this.dialogFormVisible = false
            notifySuccess(this, '修改成功')
            this.handleFilter()
          })
        }
      })
    },
    handleDelete(row, index) {
      my_confirm(this, () => {
        scoreStudentChangeDelete({ id: row.id }).then(() => {
          this.list.splice(index, 1)
          this.dialogFormVisible = false
          notifySuccess(this, '删除成功')
        })
      })
    },
    handleDownload() {
      this.downloadLoading = true
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = ['班级名称', '班级地址']
        const filterVal = ['name', 'address']
        const data = formatJson(this, filterVal)
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: '班级教室'
        })
        this.downloadLoading = false
      })
    },
    getSortClass: function(key) {
      const sort = this.listQuery.querySort
      return sort === `+${key}` ? 'ascending' : 'descending'
    },
    searchUserId: function(data) {
      this.listQuery.user_id = data.userId
    },
    searchUpdateUserId: function(data) {
      this.temp.user_id = data.userId
    }
  }
}
</script>
